package com.poi.action;


import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

import java.io.OutputStream;
import java.util.ArrayList;


/** 

 * 导出EXCEL工具类，适用于单行表头的表格 

 * @author wusq 

 * @since 2011-06-20 

 */  

public class ExportExcelUtils {  

      

    /** 

     * 导出Excel的方法 

     * @param title excel中的sheet名称 

     * @param headers 表头 

     * @param out 输出流

     * @param pattern 时间格式 

     * @throws Exception 

     */  

    public static void exportExcel(String title, String[] headers, ArrayList<String> content,  OutputStream out, String pattern) throws Exception{  

        HSSFWorkbook workbook = new HSSFWorkbook();  
        HSSFSheet sheet = workbook.createSheet(title);  
        sheet.setDefaultColumnWidth(20);  

        HSSFCellStyle style = workbook.createCellStyle();  

        style.setFillForegroundColor(HSSFColor.YELLOW.index);  
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
        HSSFFont font = workbook.createFont();  
        font.setColor(HSSFColor.BLACK.index);  
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
        style.setFont(font);  
        style.setWrapText(true);  
        //表头
        HSSFRow row = sheet.createRow(0);  
        for (int i = 0; i < headers.length; i++) {  
            HSSFCell cell = row.createCell(i);  
            cell.setCellStyle(style);  
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);  
            cell.setCellValue(text);  

        }  

        // 内容
        if(content != null){  
            int index = 1; 
            int c=0;
            for(;index<=content.size()/headers.length;){  
                row = sheet.createRow(index);  
                int cellIndex = 0;  
                for(;cellIndex<headers.length;){  
                    HSSFCell cell = row.createCell(cellIndex);  
                   HSSFRichTextString richString = new HSSFRichTextString(content.get(c) == null ? "" :content.get(c).toString());  
                   cell.setCellValue(richString);  
                    cellIndex++;  
                    c++;
                }  
                index++;  
            }     
        }  
        workbook.write(out);  

    }  

}  

